package com.laomu.shiro.realm;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import com.laomu.dao.impl.UserDAO;
import com.laomu.model.User;

/**
 * 会话认证管理
 * @ProjectName:  [act-site] 
 * @Package:      [com.laomu.shiro.PermsRealm.java]  
 * @ClassName:    [PermsRealm]   
 * @Description:  [一句话描述该类的功能]   
 * @Author:       [老木]   
 * @CreateDate:   [2016年6月21日 上午10:56:55]   
 * @UpdateUser:   [老木]   
 * @UpdateDate:   [2016年6月21日 上午10:56:55]   
 * @UpdateRemark: [说明本次修改内容]  
 * @Version:      [v1.0]
 */
public class PermsRealm extends AuthorizingRealm{
	
	@Autowired
	private UserDAO userDAO;
	private String salt;
	private Integer ecTimes;
	
	private SimpleAuthenticationInfo authenticationInfo;

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		try {
			// 获取用户登录账号信息
			String pricipal = (String) token.getPrincipal();

			// 根据用户账号查询用户
			User user = userDAO.findByUsername(new User(pricipal));
			if(user!= null){
				// 获取盐值
				salt = user.getSalt();
				// 获取加密迭代次数
				ecTimes = user.getEcTimes();
				// 设置加密
				HashedCredentialsMatcher credentialsMatcher = (HashedCredentialsMatcher) super.getCredentialsMatcher();
				credentialsMatcher.setHashAlgorithmName("MD5");
				credentialsMatcher.setHashIterations(ecTimes);
				// 创建认证信息对象
				authenticationInfo = new SimpleAuthenticationInfo(user, user.getPassword(), ByteSource.Util.bytes(salt), getName());
			}
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return authenticationInfo;
	}
	
	@Autowired
	@Override
	public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) {
        super.setCredentialsMatcher(credentialsMatcher);
    }
	
	/**
	 * 设置密码加密处理
	 */
	/*public void encrypt() {
		HashedCredentialsMatcher match = new HashedCredentialsMatcher();
		// TODO 该方法执行时，Realm数据还没有执行获取，所以ecTimes为null，密码算法赋值出错。
		if (ecTimes != null) {
			match.setHashAlgorithmName("MD5");// 设置算法
			match.setHashIterations(ecTimes);// 设置迭代次数
			
			setCredentialsMatcher(match);// 设置加密
		}
	}*/
}
